<template>
  <div class="wrapper">
    <div class="header">
      <a-form-model layout="inline" :model="searchForm" @submit="handleSubmit" @submit.native.prevent>
        <a-form-model-item label="模型名称">
          <a-input v-model="searchForm.name" placeholder="输入模型名称"> </a-input>
        </a-form-model-item>
        <a-form-model-item>
          <a-button class="border-radius-4" type="primary" icon="search" @click="pageModels"> 搜索 </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="body">
      <a-button class="operateButtons" type="primary" icon="plus" @click="showAddModal"> 新增模型 </a-button>
      <a-table :columns="columns" size="middle" :data-source="data" class="custom-table">
        <span slot="action" slot-scope="text, record, index">
          <a-button type="link" class="px-0" @click="handleGetInfo(record)"> 详情 </a-button>
          <a-divider type="vertical" />
          <a-button type="link" class="px-0" @click="handleDelete(record)"> 删除 </a-button>
        </span>
      </a-table>
    </div>
    <div class="footer"></div>

    <!-- <a-modal name="updateModal" v-model="visible" :title="modalTile" @ok="handleOk" @cancel="handleCancel" :width="800"
      okText="确认" cancelText="取消">
      <a-form-model :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="模型名称">
          <a-input v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item label="标签">
          <a-select v-model="form.labels" placeholder="选择标签">
            <a-select-option value="biaoqian1"> 标签1 </a-select-option>
            <a-select-option value="biaoqian2"> 标签2 </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="模型指标">
          <a-input v-model="form.indicator" />
        </a-form-model-item>
        <a-form-model-item label="模型保存路径">
          <a-input v-model="form.savePath" />
        </a-form-model-item>
      </a-form-model>
    </a-modal> -->

    <detail ref="detail" />

    <a-modal
      name="addModal"
      v-model="addVisible"
      :title="addModalTitle"
      @ok="handleAddOk"
      @cancel="handleAddCancel"
      :width="600"
      okText="确认"
      cancelText="取消"
      destroy-on-close
    >
      <a-form-model :model="addForm" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="模型名称">
          <a-input placeholder="输入模型名称" v-model="addForm.name" />
        </a-form-model-item>
        <a-form-model-item label="模型算法类型">
          <a-select class="custom-select" v-model="addForm.modelType" placeholder="请选择算法类型">
            <a-select-option :value="1">线性回归</a-select-option>
            <a-select-option :value="2">逻辑回归</a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { listModels, addModel, deleteModel } from '../../../api/model'
import { formatTime } from '../../../utils/util'
import notification from 'ant-design-vue/es/notification'
import detail from './detail'
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80, // 设置序号列的宽度
    customRender: (text, record, index) => `${index + 1}`, // 显示序号
  },
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '标签',
    dataIndex: 'labels',
    key: 'labels',
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    key: 'updateTime',
  },
  {
    title: '操作',
    key: 'action',
    width: 180, // 设置序号列的宽度
    scopedSlots: { customRender: 'action' },
  },
]

let data = []
export default {
  name: 'ModalDevelop',
  components: {
    detail, // 注册子组件
  },
  data() {
    return {
      formInline: {
        user: '',
        password: '',
      },
      data,
      columns,
      visible: false,

      isEdit: false,
      modalTile: '新增',
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        labels: undefined,
        indicator: undefined,
        savePath: '',
      },

      addModalTitle: '新增模型',
      addVisible: false,
      addForm: {
        name: '',
        modelType: undefined,
      },
      searchForm: {
        name: '',
      },
    }
  },
  methods: {
    generateRandomId() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
      let id = ''
      for (let i = 0; i < 4; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length)
        id += chars[randomIndex]
      }
      return id
    },
    getCurrentTime() {
      const now = new Date()

      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，因此+1
      const day = String(now.getDate()).padStart(2, '0')

      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleSubmit(e) {
      console.log(this.formInline)
    },
    showAddModal() {
      this.addVisible = true
    },
    handleOk(e) {
      console.log(this.form)
      this.data = [{ ...this.form, modalId: this.generateRandomId(), createTime: this.getCurrentTime() }, ...this.data]
      this.visible = false
      this.handleReset()
    },
    handleCancel() {
      this.visible = false
      this.handleReset()
    },
    handleReset() {
      this.form = {
        name: '',
        labels: '',
        indicator: '',
        savePath: '',
      }
    },
    handleEdit(row) {
      console.log(row)
      this.isEdit = true
      this.form = {
        ...row,
      }
      // this.showAddModal()
    },
    handleDelete(record) {
      const newThis = this
      this.$confirm({
        title: '确认删除',
        content: `确定要删除模型 "${record.name}" 吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk() {
          deleteModel({ name: record.name })
            .then((result) => {
              notification.success({
                message: '删除成功',
                description: `删除成功`,
              })
              newThis.pageModels()
            })
            .catch((error) => {
              notification.error({
                message: '删除失败',
                description: `删除失败`,
              })
            })
        },
      })
    },
    onSubmit() {
      console.log('submit!', this.form)
    },
    pageModels() {
      let requestResult = []
      listModels({ name: this.searchForm.name }).then((result) => {
        // 服务端返回的是个对象,里面的字段是个数组
        result.registered_models &&
          result.registered_models.forEach((item) => {
            let singalData = {
              key: item.name,
              name: item.name,
              labels:
                item.tags == undefined
                  ? []
                  : (() => item.tags.map((tagItem, index, array) => `${tagItem.key}:${tagItem.value}`).join(' '))(),
              modalId: 'XXX',
              createTime: formatTime(new Date(item.creation_timestamp)),
              updateTime: formatTime(new Date(item.creation_timestamp)),
            }
            requestResult.push(singalData)
          })
      })
      this.data = requestResult
    },
    // 添加重置addForm的方法
    resetAddForm() {
      this.addForm = {
        name: '',
        modelType: undefined,
      }
    },
    handleAddOk(e) {
      console.log(e)
      const newThis = this
      addModel(newThis.addForm)
        .then((result) => {
          newThis.addVisible = false
          newThis.pageModels()
          newThis.resetAddForm() // 添加重置
          notification.success({
            message: '新增成功',
            description: `新增成功`,
          })
        })
        .catch((error) => {
          newThis.addVisible = false
          newThis.resetAddForm() // 添加重置
          notification.error({
            message: '新增失败',
            description: `新增失败`,
          })
        })
    },
    handleAddCancel() {
      this.addVisible = false
      this.resetAddForm() // 添加重置
    },
    handleGetInfo(record) {
      this.$refs.detail.showModal(record)
    },
  },
  mounted() {
    this.pageModels()
  },
}
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
